package edu.gatech.cs2340.group7.wheresmystuffapp.presenters;

import java.util.ArrayList;
import java.util.List;

import edu.gatech.cs2340.group7.wheresmystuffapp.model.DataManager;
import edu.gatech.cs2340.group7.wheresmystuffapp.model.DatabaseHelper;
import edu.gatech.cs2340.group7.wheresmystuffapp.model.Item;
import edu.gatech.cs2340.group7.wheresmystuffapp.model.ItemLocation;
import edu.gatech.cs2340.group7.wheresmystuffapp.model.ItemManager;
import edu.gatech.cs2340.group7.wheresmystuffapp.views.MatchedItemView;

public class MatchedItemPresenter {

	private MatchedItemView view;
	private DatabaseHelper helper;
	private ItemManager manager;
	private List<Item> ListAllItems;
	private List<Item> ListAccountItems;
	private ArrayList<ArrayList<Item>> ListMatchedItems;

	public MatchedItemPresenter(MatchedItemView v) {
		view = v;
		helper = new DatabaseHelper(view);
		manager = new ItemManager();
	}

	/**
	 * Matches the items that the user has added to items in the database
	 */
	public void matchItems() {
		String username = DataManager.getCurrentAccountName();
		ListAllItems = helper.getAllItems();
		ListAccountItems = manager.filterByAccount(ListAllItems);
		ListMatchedItems = new ArrayList<ArrayList<Item>>();
		for (int i = 0; i < ListAccountItems.size(); i++) {
			ListMatchedItems.add(new ArrayList<Item>());
		}
		/*
		 * Match items -start with first item in ListAccountItems -go through
		 * ListAllItems -if it doesn't belong to the same account, check the
		 * name/location -if either match, add it in appropriate place in the
		 * list of items
		 */
		for (int index = 0; index < ListAccountItems.size(); index++) {
			Item i = ListAccountItems.get(index);
			for (Item item : ListAllItems) {
				// if the two items don't belong to the same account, try to
				// match them
				if (!item.getUsername().equalsIgnoreCase(username)) {
					// if either the name or locations match, add to
					// MatchedItemList
					if ((i.getName().equalsIgnoreCase(item.getName()))
							|| (i.compareTo(item) < ItemLocation.COMPARE_DISTANCE)) {
						ListMatchedItems.get(index).add(item);
					}
				}
			}
		}
		showMatchedItems();
	}

	/**
	 * Displays the list of matched items
	 */
	private void showMatchedItems() {
		/*
		 * for each item in ListAccountItems - go through ListMatchedItems at
		 * respective index, add it to result string
		 */
		String result = "";
		for (int index = 0; index < ListAccountItems.size(); index++) {
			result += ListAccountItems.get(index).getName()
					+ " matches to these items:  " + '\n';
			// go through ListMatchedItems at index, add to string
			ArrayList<Item> list = ListMatchedItems.get(index);
			for (Item i : list) {
				result += i.getName() + ", ";
			}
			result += '\n';
		}

		view.displayMatchedItems(result);
	}
}
